package ejb;

import java.util.ArrayList;
import java.util.Properties;

import javax.annotation.PreDestroy;
import javax.ejb.LocalBean;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import myJDBC.myConnection;


@Stateful
@LocalBean
public class LoginnedUserBean implements IRemoteLoginnedUserBean {

	private String login;
	private int object_id;
	private ArrayList<Integer> groupids;
	private ArrayList<String> groupnames;
	private boolean created=false;
	private Integer token;
	private IRemoteAuthValidator av;
   
    public LoginnedUserBean() {
    	Properties props = new Properties();
		Context context;
    	props.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jboss.naming.remote.client.InitialContextFactory");
		props.put(Context.PROVIDER_URL, "remote://localhost:4447");
		try {
			context = new InitialContext(props);
			av = (IRemoteAuthValidator) context.lookup("/netcracker/AuthValidator!ejb.IRemoteAuthValidator");
	    } catch (NamingException e) {
			e.printStackTrace();
		}
    }
    	

	@Override
	public void fillFields(String login, int object_id, ArrayList<Integer> groups,ArrayList<String> grnames,int token) {
		if(!created){
			this.login=login;
			this.object_id=object_id;
			this.groupids=groups;
			this.groupnames=grnames;
			this.token=token;
			created=true;
		}		
	}
	@Override
	public String getLogin() {		
		return login;
	}
	@Override
	public int getObjectId() {
		return object_id;
	}
	@Override
	public ArrayList<Integer> getGroupIds() {
		return groupids;
	}
	@Override
	public ArrayList<String> getGroupNames(){
		return groupnames;
	}
	@Override
	public Boolean checkAuthorisation(Long d) {
		if (av.checkAuth(login, token, d))
			return true;
		else 
			return false;
	}

	@Remove
	@Override
	public void removeBean() {
		av.removeAuth(login);	
		//и тут удалить его както
	}
	
	@PreDestroy
	public void connectionDrop() {
		myConnection.closeConnection();
	}
}
